package com.wl.thread.demo05;

/**
 * 不安全的银行
 */
public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account(100,"银行卡");
        Drawing you = new Drawing(account,50,"王");
        Drawing her = new Drawing(account,100,"杜");

        you.start();
        her.start();
    }
}

/**
 * 账户
 */
class Account{
    int money;
    String name;

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

/**
 * 模拟银行取款
 */
class  Drawing extends Thread{
    Account account;
    //取钱数
    int drawingMoney;
    //现在手里多少钱
    int nowMoney;

    public Drawing(Account account,int drawingMoney,String name){
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    @Override
    public void run() {
        //锁的对象是变化的量
        synchronized (account){
            if (account.money - drawingMoney < 0){
                System.out.println(Thread.currentThread().getName()+"钱不够");
                return;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            account.money = account.money - drawingMoney;
            nowMoney = nowMoney + drawingMoney;
            System.out.println(account.name+"余额为:"+account.money);
            //Thread.currentThread().getName() = this.getName()
            System.out.println(this.getName()+"手里的钱:"+nowMoney);
        }
    }
}
